package com.health.work.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.health.work.R;
import com.health.work.model.AddressBean;
import com.health.work.model.BusinessBean;
import com.health.work.parse.AddressParse;
import com.health.work.parse.TypeParse;
import com.health.work.utils.DefaultJSONData;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.RequestParamtersUtil;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.UploadUtil;
import com.health.work.utils.UserInfoUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * 项目名称：HealthNet 类名称：医师 录入信息 类描述： 创建人：Zhai 创建时间：2012-11-8 下午2:26:42 修改人：Zhai
 * 修改时间：2012-11-8 下午2:26:42 修改备注：
 * 
 * @version
 * 
 */
public class RegisteProductInfoInputActivity extends Activity implements
		OnClickListener {

	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/DCIM/Camera");

	/* 用来标识请求照相功能的activity */
	private static final int CAMERA_WITH_DATA = 3023;

	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	
	protected static final int SUCCESS_PHOTO = 10;

	protected static final int ERROR_PHOTO = 11;

	protected static final int SUCCESS = 0;

	protected static final int ERROR = 1;
	
	protected static final int NETERROR=9999;

	private File mCurrentPhotoFile;// 照相机拍照得到的图片

	private TextView back;
	private Button btnUpSeller;
	private Button btnUpProcduct;
	private Button btnUpAll;
	private String RegisteProductInfoInputActivityTag = "RegisteProductInfoInputActivity";

	private ProgressDialog dialog;
	private Spinner spinner1;
	private Spinner spinner2;
	private Spinner spinner3;
	private Spinner spinner4;
	private List<String> spinnerList1;
	private List<String> spinnerList2;
	private List<String> spinnerList3;
	private List<String> spinnerList4;
	private ArrayList<AddressBean> provinceList;
	private ArrayList<AddressBean> cityList;
	private ArrayList<AddressBean> areaList;
	private ArrayList<AddressBean> roadList;
	private String province;
	private String city;
	private String area;
	private String road="";
	private AddressParse parse;

	private Spinner spinner_product;
	private TypeParse typeParse;
	private String idBusinessType;
	
	private String passport_img="";
	private String product_img="";

	private int type_action;
	
	private EditText mainProduct;
	private EditText productName;
	private EditText address;

	private Thread thread;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case SUCCESS:
				dia();
				TipsUtil.showAlertFinish(RegisteProductInfoInputActivity.this, null,
						"恭喜您，上传信息成功！");
				break;
			case ERROR:
				dia();
				TipsUtil.showAlert(RegisteProductInfoInputActivity.this, null,
						"上传信息失败！");
				break;
			case NETERROR:
				dia();
				TipsUtil.showAlert(RegisteProductInfoInputActivity.this, null,
						"网络请求异常，请检查网络");
				break;
			case SUCCESS_PHOTO:
				TipsUtil.showAlert(RegisteProductInfoInputActivity.this, null,
						"恭喜您，上传图片成功！");
				
				break;
			case ERROR_PHOTO:
				TipsUtil.showAlert(RegisteProductInfoInputActivity.this, null,
						"上传图片失败！");
				break;
			default:
				break;
			}

		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registerproductinputinfo);
		init();
	}

	private void init() {
		btnUpSeller = (Button) this.findViewById(R.id.btnUpSeller);
		btnUpProcduct = (Button) this.findViewById(R.id.btnUpProcduct);
		btnUpAll = (Button) this.findViewById(R.id.btnUpAll);
		back = (TextView) findViewById(R.id.back);
		back.setOnClickListener(this);
		btnUpSeller.setOnClickListener(this);
		btnUpProcduct.setOnClickListener(this);
		btnUpProcduct.setVisibility(View.GONE);
		btnUpAll.setOnClickListener(this);
		
		mainProduct=(EditText)this.findViewById(R.id.main_name);
		productName=(EditText)this.findViewById(R.id.real_name);
		address=(EditText)this.findViewById(R.id.real_add);
		request("0", 1);
	}

	private void spinnerother() {// 其它的类别
		if (typeParse == null) {
			return;
		}
		spinner_product = (Spinner) this
				.findViewById(R.id.spinner_product_kink);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item,
				typeParse.nameListBusinessType);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_product.setAdapter(adapter);
		spinner_product
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int pos, long arg3) {
						idBusinessType = typeParse.typeListBusinessType
								.get(pos).TypeId;
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						idBusinessType = typeParse.typeListBusinessType.get(0).TypeId;
					}
				});
	}

	private void spinnerRelation1() {// 省
		if (spinnerList1 == null) {
			return;
		}
		spinner1 = (Spinner) this.findViewById(R.id.spinner1);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList1);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner1.setAdapter(adapter);
		spinner1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				request(provinceList.get(pos).provinceId, 2);
				province = provinceList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				province = provinceList.get(0).provinceId;
			}
		});
	}

	private void spinnerRelation2() {// 市
		if (spinnerList2 == null) {
			return;
		}
		spinner2 = (Spinner) this.findViewById(R.id.spinner2);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList2);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner2.setAdapter(adapter);
		spinner2.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				request(cityList.get(pos).provinceId, 3);
				city = cityList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				city = cityList.get(0).provinceId;
			}
		});
	}

	private void spinnerRelation3() {// 区
		if (spinnerList3 == null) {
			return;
		}
		spinner3 = (Spinner) this.findViewById(R.id.spinner3);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList3);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner3.setAdapter(adapter);
		spinner3.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				request(areaList.get(pos).provinceId, 4);
				area = areaList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				area = areaList.get(0).provinceId;
			}
		});
	}

	private void spinnerRelation4() {// 其它
		if (spinnerList4 == null) {
			return;
		}
		spinner4 = (Spinner) this.findViewById(R.id.spinner4);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList4);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner4.setAdapter(adapter);
		spinner4.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				road = roadList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				road = roadList.get(0).provinceId;
			}
		});
	}

	protected void request(final String provinceId, final int i) {
		final Context context = this;
		AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPreExecute() {
				if (dialog != null) {

				} else {
					dialog = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
					dialog.setCancelable(true);
				}

				if (typeParse == null) {
					typeParse = new TypeParse();
				}
				parse = new AddressParse();
			}

			@Override
			protected Void doInBackground(Void... params) {
				new RequestParamtersUtil().GetByUpId(provinceId, parse);
				if (typeParse.typeListBusinessType != null) {

				} else {
					new RequestParamtersUtil().GetBusiness(typeParse);
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				if (spinner_product == null) {
					spinnerother();
				}

				if (i == 1) {
					provinceList = parse.addressList;
					spinnerList1 = parse.nameList;
					spinnerRelation1();
				} else if (i == 2) {
					cityList = parse.addressList;
					spinnerList2 = parse.nameList;
					spinnerRelation2();
				} else if (i == 3) {
					areaList = parse.addressList;
					spinnerList3 = parse.nameList;
					spinnerRelation3();
				} else if (i == 4) {
					roadList = parse.addressList;
					spinnerList4 = parse.nameList;
					spinnerRelation4();
					dialog.dismiss();
					dialog = null;
				}
			}
		};
		asyncLoad.execute(null);
	}
	
	protected void upFile(final int kind,final File file,final Bitmap bitmap) {
		final Context context = this;
		AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {
			 private ProgressDialog dialog2 = null;
			 private String url="";
			@Override
			protected void onPreExecute() {
				if (dialog2 != null) {
				} else {
					dialog2 = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
					dialog2.setCancelable(true);
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if(kind==2){
					url=UploadUtil.uploadFile(file, HEALTHPASSPORT.URL_PIC,
						"file");
				}else if(kind==1){
					url=UploadUtil.uploadFile(bitmap,
							HEALTHPASSPORT.URL_PIC, "file");	
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
					dialog2.dismiss();
					dialog2 = null;
					
					if(url!=null&&url.length()>0){
						handler.sendEmptyMessage(SUCCESS_PHOTO);
						
						if(type_action==1){
							passport_img=url;
						}else if(type_action==2){
							product_img=url;
						}
						
					}else {
						handler.sendEmptyMessage(ERROR_PHOTO);
					}
					
			}
		};
		asyncLoad.execute(null);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnUpSeller:
			type_action=1;
			doPickPhotoAction();
			break;
		case R.id.btnUpProcduct:
			type_action=2;
			doPickPhotoAction();
			break;
		case R.id.liner_prouct_user:

			break;
		case R.id.back:
			finish();
			break;
		case R.id.btnUpAll:
			submit();
			break;
		default:
			break;
		}
	}

	//上传商家信息的函数，暂时设计上是没有这个按钮的
	private void submit() {
		final BusinessBean bus=new BusinessBean();
		bus.MobilePhone=UserInfoUtils.getUserProperty(this, HEALTHPASSPORT.MOBILEPHONE);
		bus.Province=province;
		bus.City=city;
		bus.CountyArea=area;
		bus.Township=road;
		bus.BusinessTypeId=idBusinessType;
		if(!TipsUtil.isNull(mainProduct)&&!TipsUtil.isNull(address)&&!TipsUtil.isNull(productName)){
			
		}else{
			TipsUtil.showAlert(this, null, "主营商品，商家名称或者地址输入不正确！");
			return;
		}
		bus.MainCommodities=mainProduct.getText().toString();
		bus.BusinessAddress=address.getText().toString();
		bus.Name=productName.getText().toString();
		if(passport_img!=null && passport_img.length()>0){
			bus.photo=passport_img;
//			if(product_img!=null && product_img.length()>0){
//				bus.photo=bus.photo+";"+product_img;
//			}
		}else{
//			bus.photo=product_img;
		}
		if(!TipsUtil.isNull(bus.photo)){
			
		}else{
			TipsUtil.showAlert(this, null, "请上传营业执照！");
			bus.photo=null;
			return;
		}
		dia();
		new Thread(new Runnable() {
				@Override
				public void run() {
					new RequestParamtersUtil().SaveBusiness(bus, new DefaultJSONData() {
	
								@Override
								public void parse(JSONObject object)
										throws JSONException {
									handler.sendEmptyMessage(ERROR);
								}
	
								@Override
								public void parse(JSONArray array)
										throws JSONException {
									handler.sendEmptyMessage(ERROR);
								}
	
								@Override
								public void parse(String result)
										throws JSONException {
									Log.e("SaveBusiness", result);
									if("1".equals(result)){
										handler.sendEmptyMessage(ERROR);
									}else if("0".equals(result)){
										handler.sendEmptyMessage(SUCCESS);
									}else if("9999".equals(result)){
										handler.sendEmptyMessage(NETERROR);
									}
								}
							});
					
				}
			}).start();

	}
	
	private void dia(){
		if (dialog != null) {
			dialog.cancel();
			dialog=null;
		} else {
			dialog = ProgressDialog.show(this, "", "正在加载数据，请稍候...");
			dialog.setCancelable(true);
		}
	}

	/**
	 * 
	 * 88888888888888888888888888888888888888888888888888888888888888888888888888
	 */

	// 以下代码是调用摄像头或者系统相册

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e(RegisteProductInfoInputActivityTag, "1:" + requestCode + "  2:"
				+ resultCode);
		if (resultCode != Activity.RESULT_OK)
			return;
		switch (requestCode) {
			case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
				final Bitmap photo = data.getParcelableExtra("data");
				System.out.println(photo);
//				String imageStr = BitmapBase64.getBitmapStringBase64(photo);
				upFile(1,null,photo);
				break;
			}
			case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
			// doCropPhoto(mCurrentPhotoFile);
				upFile(2,mCurrentPhotoFile,null);
				break;
			}
		}
	}

	public void doPickPhotoAction() {
		final Context dialogContext = new ContextThemeWrapper(this,
				android.R.style.Theme_Light);
		String cancel = "返回";
		String[] choices;
		choices = new String[2];
		choices[0] = "拍照"; // 拍照
		choices[1] = "从相册中选择"; // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle("选择方式");
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0: {
							String status = Environment
									.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							} else {
								Toast.makeText(
										RegisteProductInfoInputActivity.this,
										"出现异常", Toast.LENGTH_LONG).show();
							}
							break;

						}
						case 1:
							doPickPhotoFromGallery();// 从相册中去获取
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			mCurrentPhotoFile = new File(PHOTO_DIR, "health.jpg");// 给新照的照片文件命名
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	// 请求Gallery程序
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	// 封装请求Gallery的intent
	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	protected void doCropPhoto(File f) {
		try {
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (Exception e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 *  调用图片剪辑程序
	 */
	public static Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

}
